var express = require('express');
var _ = require("underscore");
var Page = require('../models/page');
    //codeState = boxSim.codeState;
var Box = require('../models/boxes');
var Buyer = require('../models/buyer');
var Sim = require('../models/sim');
var Log = require('../models/log');
var BoxBuyer = require('../models/box_buyer');
var User = require('../models/user');
var mqtt = require('mqtt');
var async=require('async');
var Billing=require('../models/billing');
var Fault = require('../models/fault');
require('date-utils');
/* GET home page. */

module.exports = function(app) {
    app.get('/',function(req,res){
        res.render('index',{
            sess:0
        });
    });

    app.post('/',function(req,res){
        var username=req.body.username;
        var password = req.body.pwd;
        if(username=="admin"){
            new User().findUserByName(username,function(err,datas){
                if(err){
                    return res.render('index',{
                        name:username,
                        pwd:req.body.password,
                        error:'服务器繁忙，请稍后再试！'
                    });
                }
                if(datas){
                    if(password!=datas.password){
                        return res.render('index',{
                            username:username,
                            pwd:req.body.password,
                            error:'密码不正确，请重新输入！'
                        });
                    }
                    new Log({
                        box_id: " ",
                        user: "管理员", //操作人
                        date: new Date(), //操作日期
                        operation: "登陆系统" //操作内容
                    }).save();
                    req.session.user=datas;
                    req.flash('success', '登陆成功.');
                    return res.redirect('/box_management');
                }
            })
        }else{
            new Buyer().findAccountByAccount(username,function(err,doc) {
                if (doc) {
                    if (password != doc.password) {
                        return res.render('index', {
                            username: username,
                            pwd: req.body.password,
                            error: '密码不正确，请重新输入！'
                        });
                    }else{
                        req.session.user=doc;
                        //req.flash('success', '登陆成功.');
                        return res.redirect('/user_system?account='+username+'&&state=ok');
                    }
                }else{
                    return res.render('index', {
                        name: username,
                        pwd: req.body.password,
                        error: '用户名不存在，请重新输入'
                    });
                }
            });
        }
    });
    app.get('/user_system',function(req,res){
        var account=req.query.account;
            res.render('user_system',{
                account:account
            });
    });
    //购买人箱子管理页面
    app.get('/user_system/buyer_box',function(req,res){
        var account=req.query.account;
        new Buyer().findAccountByAccount(account,function(err,doc){
            var buyer_id=doc.buyer_id;
            new BoxBuyer().findIdsByBuyer(buyer_id,function(datas) {
                if (datas.length > 0) {
                    var boxes=[];
                    for(var i=0;i<datas.length;i++){
                        boxes.push(datas[i].box_id);
                    }
                    var options={box_id:{$in:boxes}};
                    var page = new Page(req.query.num);
                    var obj = {
                        page: page,
                        search: options
                    };
                    console.log(boxes);
                        new Box().findForPage(obj, function (err, count, pageCount, datas) {
                            var box = datas;
                            page.pageCount = pageCount;
                            res.render('buyer_box', {
                                datas: box,
                                buyerid:buyer_id,
                                account:account,
                                page:page
                            });
                        });
                }else{
                    req.flash('error', '您没有绑定箱子.');
                    return res.redirect('/user_system/main');
                }
            });
        });
    });
    //购买人箱子详情页面
    app.get('/user_system/userbox_order',function(req,res){
        var boxid=req.query.boxid;
        var buyerid=req.query.buyerid;
        new Box().findBoxById(boxid,function(datas){
            var boxDatas=datas;
            new Sim().findSimById(boxid,function(datas){
                var simDatas=datas;
                new Buyer().findById(buyerid,function(datas){
                    var buyerdatas=datas;
                    res.render('userbox_order',{
                        simdatas:simDatas,
                        boxdatas:boxDatas[0],
                        buyerdatas:buyerdatas
                    });
                });
            });
        });
    });
    //用户门状态页面
    app.get('/user_system/user_doors',function(req,res){
        var boxid=req.query.boxid;
        var index=req.query.index;
        if(index==0) {
            new Box().findByBoxId(boxid, function (data) {
                var list = data;
                res.render("user_door", {
                    "boxid": boxid,
                    "doordatas": list
                });
            });
        }else if(index=="all"){
            var doorsnum=req.query.doorsnum;
            var doors = [];
            for (var i = 0; i < doorsnum; i++) {
                doors.push({
                    index: i + 1,
                    empty: true,
                    password: "",
                    opentime: "",
                    owner: ""
                });
            }
            new Box().updateDoorById(boxid,doors,function(){
                Box().findByBoxId(boxid, function(data) {
                    var list = data;
                    res.render("user_door", {
                        "boxid": boxid,
                        "doordatas": list
                    });
                });
            });
        }else{
            new Box().updateByBoxidAndIndex(boxid, index,function(data){
                Box().findByBoxId(boxid, function(data) {
                    var list = data;
                    res.render("user_door", {
                        "boxid": boxid,
                        "doordatas": list
                    });
                });
            });
        }
    });
    //设置计费页面
    app.get('/user_system/billing',function(req,res){
        var boxid=req.query.boxid;
        var account=req.query.account;
        new Billing().findSpriceById(boxid,function(datas){
            if(datas==""){
                res.render('billing',{
                    boxid:boxid,
                    account:account,
                    pri:0
                });
            }else{
                var standard=datas[0].standard;
                var price=datas[0].price;
                var less=datas[0].less;
                var lessprice=datas[0].lessprice;
                var more=datas[0].more;
                var moreprice=datas[0].moreprice;
                res.render('billing',{
                    boxid:boxid,
                    account:account,
                    pri:1,
                    standard:standard,
                    price:price,
                    less:less,
                    lessprice:lessprice,
                    more:more,
                    moreprice:moreprice
                });
            }
        });
    });
    //提交计费设置
    app.post('/user_system/billing',function(req,res){
        var boxid=req.body.boxid;
        var account=req.body.account;
        var standard = req.body.standard;
        var timetype = req.body.timetype;
        var price = req.body.price;
        var less = req.body.less;
        var lesstimetype = req.body.lesstimetype;
        var lessprice = req.body.lessprice;
        var more = req.body.more;
        var moretimetype = req.body.moretimetype;
        var moreprice = req.body.moreprice;
        if(less==""&&more==""){
            console.log(less+"---null");
            if(timetype==1){
            new Billing().removepriceById(boxid,function(err){
                var stan=standard*60;
                new Billing({
                    box_id: boxid,
                    standard:stan,
                    price: price,
                    less: less,
                    lessprice:lessprice,
                    more:more,
                    moreprice:moreprice
                }).save();
            });

            }else if(timetype==0){
                new Billing().removepriceById(boxid,function(err){
                    new Billing({
                        box_id: boxid,
                        standard:standard,
                        price: price,
                        less: less,
                        lessprice:lessprice,
                        more:more,
                        moreprice:moreprice
                    }).save();
                });
            }
        }else if(less==""&&more!==""){
            if(timetype==1){
                var stans=standard*60;
                if(moretimetype==1){
                    new Billing().removepriceById(boxid,function(err){
                        var mor=more*60;
                        new Billing({
                            box_id: boxid,
                            standard:stans,
                            price: price,
                            less: less,
                            lessprice:lessprice,
                            more:mor,
                            moreprice:moreprice
                        }).save();
                    });

                }else if(moretimetype==0){
                    new Billing().removepriceById(boxid,function(err){
                        new Billing({
                            box_id: boxid,
                            standard:stans,
                            price: price,
                            less: less,
                            lessprice:lessprice,
                            more:more,
                            moreprice:moreprice
                        }).save();
                    });
                }
            }else if(timetype==0){
                if(moretimetype==1){
                    new Billing().removepriceById(boxid,function(err){
                        var mor=more*60;
                        new Billing({
                            box_id: boxid,
                            standard:standard,
                            price: price,
                            less: less,
                            lessprice:lessprice,
                            more:mor,
                            moreprice:moreprice
                        }).save();
                    });

                }else if(moretimetype==0){
                    new Billing().removepriceById(boxid,function(err){
                        new Billing({
                            box_id: boxid,
                            standard:standard,
                            price: price,
                            less: less,
                            lessprice:lessprice,
                            more:more,
                            moreprice:moreprice
                        }).save();
                    });
                }
            }
        }else if(less!==""&&more==""){
            if(timetype==1){
                var sta=standard*60;
                if(lesstimetype==1){
                    new Billing().removepriceById(boxid,function(err){
                        var les=less*60;
                        new Billing({
                            box_id: boxid,
                            standard:sta,
                            price: price,
                            less: les,
                            lessprice:lessprice,
                            more:mor,
                            moreprice:moreprice
                        }).save();
                    });

                }else if(lesstimetype==0){
                    new Billing().removepriceById(boxid,function(err){
                        new Billing({
                            box_id: boxid,
                            standard:sta,
                            price: price,
                            less: less,
                            lessprice:lessprice,
                            more:more,
                            moreprice:moreprice
                        }).save();
                    });
                }
            }else if(timetype==0){
                if(lesstimetype==1){
                    new Billing().removepriceById(boxid,function(err){
                        var le=less*60;
                        new Billing({
                            box_id: boxid,
                            standard:standard,
                            price: price,
                            less: le,
                            lessprice:lessprice,
                            more:more,
                            moreprice:moreprice
                        }).save();
                    });

                }else if(moretimetype==0){
                    new Billing().removepriceById(boxid,function(err){
                        new Billing({
                            box_id: boxid,
                            standard:standard,
                            price: price,
                            less: less,
                            lessprice:lessprice,
                            more:more,
                            moreprice:moreprice
                        }).save();
                    });
                }
            }
        }else if(less!==""&&more!==""){
            if(timetype==1){
                var st=standard*60;
                if(lesstimetype==1){
                    var lesss=less*60;
                    if(moretimetype==1){
                        new Billing().removepriceById(boxid,function(err){
                            var moree=more*60;
                            new Billing({
                                box_id: boxid,
                                standard:st,
                                price: price,
                                less: lesss,
                                lessprice:lessprice,
                                more:moree,
                                moreprice:moreprice
                            }).save();
                        });

                    }else if(moretimetype==0){
                        new Billing().removepriceById(boxid,function(err){
                            new Billing({
                                box_id: boxid,
                                standard:st,
                                price: price,
                                less: lesss,
                                lessprice:lessprice,
                                more:more,
                                moreprice:moreprice
                            }).save();
                        });
                    }
                }else if(lesstimetype==0){
                    if(moretimetype==1){
                        new Billing().removepriceById(boxid,function(err){
                            var moreee=more*60;
                            new Billing({
                                box_id: boxid,
                                standard:st,
                                price: price,
                                less: less,
                                lessprice:lessprice,
                                more:moreee,
                                moreprice:moreprice
                            }).save();
                        });

                    }else if(moretimetype==0){
                        new Billing().removepriceById(boxid,function(err){
                            new Billing({
                                box_id: boxid,
                                standard:st,
                                price: price,
                                less: less,
                                lessprice:lessprice,
                                more:more,
                                moreprice:moreprice
                            }).save();
                        });
                    }
                }
            }else if(timetype==0){
                if(lesstimetype==1){
                    var lessss=less*60;
                    if(moretimetype==1){
                        new Billing().removepriceById(boxid,function(err){
                            var moreeeee=more*60;
                            new Billing({
                                box_id: boxid,
                                standard:standard,
                                price: price,
                                less: lessss,
                                lessprice:lessprice,
                                more:moreeeee,
                                moreprice:moreprice
                            }).save();
                        });

                    }else if(moretimetype==0){
                        new Billing().removepriceById(boxid,function(err){
                            new Billing({
                                box_id: boxid,
                                standard:standard,
                                price: price,
                                less: lessss,
                                lessprice:lessprice,
                                more:more,
                                moreprice:moreprice
                            }).save();
                        });
                    }
                }else if(lesstimetype==0){
                    if(moretimetype==1){
                        new Billing().removepriceById(boxid,function(err){
                            var moreeeeee=more*60;
                            new Billing({
                                box_id: boxid,
                                standard:standard,
                                price: price,
                                less: less,
                                lessprice:lessprice,
                                more:moreeeeee,
                                moreprice:moreprice
                            }).save();
                        });

                    }else if(moretimetype==0){
                        new Billing().removepriceById(boxid,function(err){
                            new Billing({
                                box_id: boxid,
                                standard:standard,
                                price: price,
                                less: less,
                                lessprice:lessprice,
                                more:more,
                                moreprice:moreprice
                            }).save();
                        });
                    }
                }
            }
        }
        req.flash('success', '费用设置成功.');
        return res.redirect('/user_system/buyer_box?num=1&&boxid='+boxid+'&&account='+account);
    });

    app.get('/box_management/update_pwd',function(req,res){
        res.render('update_pwd',{
        });
    });

    app.post('/box_management/update_pwd',function(req,res){
        var opwd=req.body.opwd;
        var password=req.body.npwd1;
        var admin="admin";
        new User().findUserByName(admin,function(err,datas){
            if(err){
                return res.render('update_pwd',{
                    error:'服务器繁忙，请稍后再试！'
                });
            }
            if(datas) {
                if (opwd != datas.password) {
                    return res.render('update_pwd', {
                        error: '旧密码不正确，请重新输入！'
                    });
                }
                new User().updatePwd(admin,password,function(err){
                    console.log(err);
                    new User().findUserByName(admin,function(err,datas){
                        req.session.user=datas;
                        new Log({
                            box_id: " ",
                            user: "管理员", //操作人
                            date: new Date(), //操作日期
                            operation: "修改管理员密码" //操作内容
                        }).save();
                        req.flash('success', '密码修改成功.');
                        return res.redirect('/box_management/update_pwd');
                    });

                });
            }
        });
    });
    app.get('/box_management',function(req,res){
        res.render('box_management');
    });
    app.get('/box_management/main',function(req,res){
        res.render('main');
    });
    app.get('/user_system/main',function(req,res){
        res.render('main');
    });

    app.get('/logout',function(req,res){
        new Log({
            box_id: " ",
            user: "管理员", //操作人
            date: new Date(), //操作日期
            operation: "退出系统" //操作内容
        }).save();
        req.session.user=null;
        res.redirect('/');
    });

    app.get('/user_logout',function(req,res){
        req.session.user=null;
        res.redirect('/');
    });

    app.get('/box_management/log', function(req, res) {
        var sess=req.session.user;
        console.log(sess.user+"------------");
        var page = new Page(req.query.num);
        var obj = {
            page: page,
            search: {}
        };
        new Log().findForPage(obj, function(err, count, pageCount, datas) {
            if (err) {
                console.log("------------" + err);
            }
            page.pageCount = pageCount;
            var dates=[];
            for(var i=0;i<datas.length;i++){
                dates.push((datas[i].date).toFormat('YYYY-MM-DD HH24:MI:SS'));
            }
            res.render('log', {
                datas: datas,
                dates:dates,
                page: page
            });
        })
    });
    app.get('/box_management/main', function(req, res) {
        res.render('main', {});
    });
    //Sim卡页面
    app.get('/box_management/code', function(req, res) {
        var sim = req.query.sim;
        console.log(sim);
        var page = new Page(req.query.num);
        var obj = {
            page: page,
            search: {}
        };
        new Sim().findForPage(obj, function(err, count, pageCount, datas) {
            if (err) {
                console.log("------------" + err);
            }
            page.pageCount = pageCount;
            res.render('qrcodeM', {
                datas: datas,
                page: page
            });
        })
        if (sim == "ok") {
            console.log("进入二维码管理");

        } else {
            //修改Sim卡打印次数
            new Sim().updateStateBySim(sim, function(err) {
                console.log(err);
            });
            //操作记录
            new Log({
                box_id: " ",
                user: "管理员", //操作人
                date: new Date(), //操作日期
                operation: "打印二维码,号码为:"+sim+"" //操作内容
            }).save();

        }
    });
    //生成Sim卡页面
    app.get('/box_management/create_sim',function(req,res){
        res.render('create_sim');
    });

    //提交Sim卡生成
    app.post('/box_management/create_sim',function(req,res){
        var sim=req.body.sim;
        var operators=req.body.operators;
        var charge=req.body.charge;
        new Sim().findSimBySim(sim, function(err, doc) {
            if (doc) err = 'Sim卡已被使用,请重新输入.';
            if (err) {
                req.flash('error', err);
                return res.redirect('/box_management/create_sim');
            }
            var nSim = new Sim({
                box_id:"未绑定",
                sim: sim,
                state: 0,
                operators: operators, //sim卡所属运营商
                charge: charge //资费
            });
            nSim.save(function(err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log("OK!");
                }
            });
            new Log({
                box_id: "",
                user: "管理员", //操作人
                date: new Date(), //操作日期
                operation: "生成Sim卡(卡号为:"+sim+")" //操作内容
            }).save();
            req.flash('success', 'Sim卡已经生成.');
            return res.redirect('/box_management/code?num=1&&sim=ok');
        });
    });

    //箱子自定义生成
    app.post('/box_management/create',function(req,res){
        var sim=req.body.sim;//获取sim卡号
        var buyer=req.body.buyer;//获取购买人姓名
        var box_layout=req.body.boxlayout;//获取箱子布局
        var doorsnum=req.body.doorNum;//获取格子数
        var codelayout=req.body.code_layout;//获取贴码位置
        var tim=new Date().getTime();
        var boxid="SB_"+tim;
        var doors = [];
        for (var i = 0; i < doorsnum; i++) {
            doors.push({
                index: i + 1,
                empty: true,
                password: "",
                opentime: "",
                owner: "",
                use:0
            });
        }
        if(buyer==0){
            var nBox = new Box({
                box_id: boxid,
                code_layout: codelayout,
                doors_num: doorsnum,
                box_layout: box_layout,
                doors: doors
            });
            nBox.save(function (err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log("OK!");
                }
            });
            new Sim().updateIdBySim(sim,boxid,function(err){});
        }else {
            var nBox = new Box({
                box_id: boxid,
                code_layout: codelayout,
                doors_num: doorsnum,
                box_layout: box_layout,
                doors: doors
            });

            nBox.save(function (err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log("OK!");
                }
            });
            new Buyer().findBuyerById(buyer,function(datas){
                var buyer_id=datas.buyer_id;
                var nBoxBuyer = new BoxBuyer({
                    buyer_id:buyer_id,
                    box_id: boxid
                });
                nBoxBuyer.save(function (err) {});
            });
            new Sim().updateIdBySim(sim,boxid,function(err){});
        }
        new Log({
            box_id: boxid,
            user: "管理员", //操作人
            date: new Date(), //操作日期
            operation: "自定义生成箱子(格子数为:"+doorsnum+")" //操作内容
        }).save();
        req.flash('success', '箱子已经生成.');
        return res.redirect('/box_management/box?num=1');
    });

    //箱子管理界面
    app.get('/box_management/box',function(req,res){
        var page = new Page(req.query.num);
        var obj = {
            page: page,
            search: {}
        };
        new Box().findForPage(obj, function(err, count, pageCount, datas) {
            if (err) {
                console.log("boxM-----" + err);
            }
            var boxdatas=datas;
            page.pageCount = pageCount;
            res.render('boxM', {
                datas: boxdatas,
                page: page
            });
        })
    });
    //自定义生成箱子页面
    app.get('/box_management/create',function(req,res){
        new Buyer().findAll(function(datas){
            var buyerdatas=datas;
            new Sim().findAllSim(function(datas){
                var simdatas=datas;
                res.render('create',{
                    buyerdatas:buyerdatas,
                    simdatas:simdatas
                });
            });
        });
    });
    //编辑箱子页面
    app.get('/box_management/edit',function(req,res){
        var boxid=req.query.boxid;
        new BoxBuyer().findBuyerById(boxid,function(datas){
            if(datas==null){
                new Buyer().findAll(function(datas){
                    var buyerdatas=datas;
                    new Sim().findAllSim(function(datas){
                        var simdatas=datas;
                        var buyer="请选择用户名";
                        new Sim().findSimById(boxid,function(datas){
                            var sim=datas.sim;
                            new Box().findBoxById(boxid,function(datas){
                                var boxdatas=datas;
                                res.render('edit',{
                                    buyerdatas:buyerdatas,
                                    simdatas:simdatas,
                                    boxid:boxid,
                                    buyer:buyer,
                                    sim:sim,
                                    boxdatas:boxdatas
                                });
                            });
                        });
                    });
                });
            }else{
                var buyerid=datas.buyer_id;
                new Buyer().findAll(function(datas){
                    var buyerdatas=datas;
                    new Sim().findAllSim(function(datas){
                        var simdatas=datas;
                        new Buyer().findById(buyerid,function(datas){
                            var buyer=datas.buyer;
                            new Sim().findSimById(boxid,function(datas){
                                var sim=datas.sim;
                                new Box().findBoxById(boxid,function(datas){
                                    var boxdatas=datas;
                                    res.render('edit',{
                                        buyerdatas:buyerdatas,
                                        simdatas:simdatas,
                                        boxid:boxid,
                                        buyer:buyer,
                                        sim:sim,
                                        boxdatas:boxdatas
                                    });
                                });
                            });
                        });

                    });
                });
            }
        });
    });
    //提交编辑后的箱子信息
    app.post('/box_management/edit',function(req,res){
        var boxid=req.body.boxid;
        var sim=req.body.sim;
        var buyer=req.body.buyer;
        var code_layout=req.body.code_layout;
        var door_num=req.body.door_num;
        var box_layout=req.body.box_layout;
        var osim=req.body.osim;

        //修改用户名
        if(buyer==0){
            new BoxBuyer().removeBuyerById(boxid,function(err){});
        }else{
            new BoxBuyer().removeBuyerById(boxid,function(err){});
            new Buyer().findBuyerById(buyer,function(datas){
                var buyer_id=datas.buyer_id;
                 var nBoxBuyer=new BoxBuyer({
                        box_id:boxid,
                        buyer_id:buyer_id
                });
                nBoxBuyer.save();
            });
        }
        //修改Sim卡号
        if(sim==0){
            console.log("没有修改Sim卡");
        }else{
            var nboxid="未绑定";
            new Sim().updateIdBySim(osim,nboxid,function(err){});
            new Sim().updateIdBySim(sim,boxid,function(err){});
        }
        //修改箱子信息
        if(code_layout==0){
            if(door_num==0){

            }else{
                var doors = [];
                for (var i = 0; i < door_num; i++) {
                    doors.push({
                        index: i + 1,
                        empty: true,
                        password: "",
                        opentime: "",
                        owner: ""
                    });
                }
                new Box().updateDoorNumById(boxid,doors,door_num,box_layout,function(err){
                    console.log(err+"-----------");
                });
            }
        }else{
            if(door_num==0){
                new Box().updateCodeById(boxid,code_layout,function(err){});
            }else{
                var doors = [];
                for (var i = 0; i < door_num; i++) {
                    doors.push({
                        index: i + 1,
                        empty: true,
                        password: "",
                        opentime: "",
                        owner: ""
                    });
                }
                new Box().updateAllById(boxid,doors,door_num,box_layout,code_layout,function(err){
                    console.log(err+"-----------");
                });
            }
        }
        new Log({
            box_id: boxid,
            user: "管理员", //操作人
            date: new Date(), //操作日期
            operation: "箱子信息更新成功" //操作内容
        }).save();
        req.flash('success', '箱子信息更新成功.');
        res.redirect('/box_management/box?num=1');
    });

    //箱子详情页面
    app.get('/box_management/box_order',function(req,res){
        var boxid=req.query.boxid;
        new Box().findBoxById(boxid,function(datas){
            var boxDatas=datas;
            console.log(boxDatas);
            new Sim().findSimById(boxid,function(datas){
                var simDatas=datas;
                new BoxBuyer().findBuyerById(boxid,function(datas){
                      if(datas==null){
                          var datas=0;
                          res.render('box_order',{
                              simdatas:simDatas,
                              boxdatas:boxDatas,
                              buyerdatas:datas
                          });
                      }else{
                          var buyer_id=datas.buyer_id;
                          new Buyer().findById(buyer_id,function(datas){
                              var buyerdatas=datas;
                              res.render('box_order',{
                                  simdatas:simDatas,
                                  boxdatas:boxDatas,
                                  buyerdatas:buyerdatas
                              });
                          });
                      }
                });
            });
        });
    });
    //修改Sim卡页面
    app.get('/box_management/update_sim',function(req,res){
        var sim=req.query.sim;
        res.render('update_sim',{sim:sim
        });
    });
    app.post('/box_management/update_sim',function(req,res){
        var sim=req.body.sim;
        var charge=req.body.charge;
        var operators=req.body.operators;
        new Sim().updateAllBySim(sim,operators,charge,function(err){
            console.log("修改Sim卡信息成功");
        });
        new Sim().findIdBySim(sim,function(datas){
            if(datas){
               var boxid=datas.box_id;
                new Log({
                    box_id: boxid,
                    user: "管理员", //操作人
                    date: new Date(), //操作日期
                    operation: "更新Sim卡资料" //操作内容
                }).save();
            }else{
                new Log({
                    box_id: "",
                    user: "管理员", //操作人
                    date: new Date(), //操作日期
                    operation: "更新Sim卡资料" //操作内容
                }).save();
            }
        });
        req.flash('success', 'Sim卡信息更新成功.');
        return res.redirect('/box_management/code?num=1&&sim=ok');
    });
    //门状态页面
    app.get('/box_management/doors',function(req,res){
        var boxid=req.query.boxid;
        var index=req.query.index;
        if(index==0) {
            new Box().findByBoxId(boxid, function (data) {
                var list = data;
                res.render("doors", {
                    "boxid": boxid,
                    "doordatas": list
                });
            });
        }else if(index=="all"){
            var doorsnum=req.query.doorsnum;
            var doors = [];
            for (var i = 0; i < doorsnum; i++) {
                doors.push({
                    index: i + 1,
                    empty: true,
                    password: "",
                    opentime: "",
                    owner: ""
                });
            }
            new Box().updateDoorById(boxid,doors,function(){
                Box().findByBoxId(boxid, function(data) {
                    var list = data;
                    res.render("doors", {
                        "boxid": boxid,
                        "doordatas": list
                    });
                });
            });
                new Log({
                    box_id: boxid,
                    user: "管理员", //操作人
                    date: new Date(), //操作日期
                    operation: "打开箱子门:所有" //操作内容
                }).save();
        }else{
            new Box().updateByBoxidAndIndex(boxid, index,function(data){
                Box().findByBoxId(boxid, function(data) {
                    var list = data;
                    res.render("doors", {
                        "boxid": boxid,
                        "doordatas": list
                    });
                });
                    var sim=data.sim;
                    new Log({
                        box_id: boxid,
                        user: "管理员", //操作人
                        date: new Date(), //操作日期
                        operation: "打开箱子门:"+index+"号" //操作内容
                    }).save();
            });
        }
    });

    //用户管理页面
    app.get('/box_management/buyer',function(req,res){
        var page = new Page(req.query.num);
        var obj = {
            page: page,
            search: {}
        };
        new Buyer().findForPage(obj, function(err, count, pageCount, datas) {
            if (err) {
                console.log("buyerM-----" + err);
            }
            page.pageCount = pageCount;
            res.render('buyerM', {
                datas: datas,
                page: page
            });
        })
    });
    //更新用户资料页面
    app.get('/box_management/update_buyer',function(req,res){
        var id=req.query.id;
        var buyer=req.query.buyer;
        var phoneNum=req.query.phoneNumber;
        var company=req.query.company;
        var level=req.query.level;
        res.render('update_buyer',{
            id:id,
            buyer:buyer,
            phoneNumber:phoneNum,
            company:company,
            level:level
        });
    });
    //提交更新buyer的资料
    app.post('/box_management/update_buyer',function(req,res){
        var id=req.body.id;
        var phoneNumber=req.body.phoneNumber;
        var buyer=req.body.buyer;
        var company=req.body.company;
        var level=req.body.level;
        //修改buyer的资料
        new Buyer().updateBuyerById(id, buyer, phoneNumber, company, level,function (err) {
            new Buyer().findBuyerBy_Id(id,function(datas){
                var buyer_id=datas.buyer_id;
                new BoxBuyer().findIdByBuyer(buyer_id,function(datas){
                    if(datas){
                        for(var i=0;i<datas.length;i++){
                            new Log({
                                box_id: datas[i].box_id,
                                user: "管理员", //操作人
                                date: new Date(), //操作日期
                                operation: "更新用户资料" //操作内容
                            }).save();
                        }
                    }else{
                        new Log({
                            box_id: "",
                            user: "管理员", //操作人
                            date: new Date(), //操作日期
                            operation: "更新用户资料" //操作内容
                        }).save();
                    }
                });
            });
            req.flash('success', '用户资料更新成功.');
            return res.redirect('/box_management/buyer?num=1');
        });
    });
    //新建用户
    app.get('/box_management/create_buyer',function(req,res){
        res.render('create_buyer',{

        });
    });
    //提交新用户资料
    app.post('/box_management/create_buyer',function(req,res){
        var buyer=req.body.buyer;
        var phoneNumber=req.body.phoneNumber;
        var username=req.body.username;
        var password=req.body.password;
        var company=req.body.company;
        var tim=new Date().getTime();
        var nBuyer = new Buyer({
            buyer_id:tim,
            buyer: buyer,
            account:username,
            password:password,
            phoneNumber: phoneNumber, //购买人联系电话
            company: company //购买人所属公司
        });
        new Buyer().findBuyerByBuyer(buyer, function(err, doc) {
            if (doc) err = '用户名已存在,请重新输入.';
            if (err) {
                req.flash('error', err);
                return res.redirect('/box_management/create_buyer?');
            }
            new Buyer().findAccountByAccount(username,function(err,doc){
                if (doc) err = '登陆账号已存在,请重新输入.';
                if (err) {
                    req.flash('error', err);
                    return res.redirect('/box_management/create_buyer?');
                }
                nBuyer.save(function(err) {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log("OK!");
                    }
                    new Log({
                        box_id:"",
                        user: "管理员", //操作人
                        date: new Date(), //操作日期
                        operation: "新建用户(用户名为:"+buyer+")" //操作内容
                    }).save();
                    req.flash('success', '新用户已经生成.');
                    return res.redirect('/box_management/create_buyer');
                });
            });
        });
    });
    //删除Sim卡
    app.get('/box_management/remo_sim',function(req,res){
        var sim=req.query.sim;
        new Sim().findIdBySim(sim,function(datas){
            if(datas.box_id=="未绑定"){
                new Sim().removeSimBySim(sim,function(err){
                    new Log({
                        box_id:"",
                        user: "管理员", //操作人
                        date: new Date(), //操作日期
                        operation: "删除Sim卡(号码名为:"+sim+")" //操作内容
                    }).save();
                    req.flash('success', '删除Sim卡成功.');
                    return res.redirect('/box_management/code?num=1&&sim=ok');
                });
            }else{
                req.flash('error', '此Sim卡已绑定箱子，不可删除.');
                return res.redirect('/box_management/code?num=1&&sim=ok');
            }
        });
    });
    //删除用户
    app.get('/box_management/remo_buyer',function(req,res){
        var buyerid=req.query.buyerid;
        var buyer=req.query.buyer;
        new BoxBuyer().findIdByBuyer(buyerid,function(datas){
            console.log(datas.length);
            if(datas==0){
                new Buyer().removeById(buyerid,function(err){
                });
                new Log({
                    box_id:"",
                    user: "管理员", //操作人
                    date: new Date(), //操作日期
                    operation: "删除用户(用户名为:"+buyer+")" //操作内容
                }).save();
                req.flash('success', '删除用户成功.');
                return res.redirect('/box_management/buyer?num=1');
            }else{
                req.flash('error', '此用户已绑定箱子，不可删除.');
                return res.redirect('/box_management/buyer?num=1');
            }
        });
    });

    //MQTT
    client = mqtt.createClient(1883, '114.215.137.61');
    client.subscribe('fault');
//    client.publish('fault', ' 3');
//    client.publish('fault', '13678039956 1');
    client.on('message', function (topic, message) {
        console.log(message.split(' ')[0]+"----------"+message.split(' ')[1]);
        if(message.split(' ')[1]==1){
            new Fault({
                sim:message.split(' ')[0],
                date: new Date(),
                ftype: message.split(' ')[1], //操作内容
                content: "连不上互联网"
            }).save();
        }else if(message.split(' ')[1]==2){
            new Fault({
                sim:message.split(' ')[0],
                date: new Date(),
                ftype: message.split(' ')[1], //操作内容
                content: "连不上服务器"
            }).save();
        }else if(message.split(' ')[1]==3){
            new Fault({
                sim:message.split(' ')[0],
                date: new Date(),
                ftype: message.split(' ')[1], //操作内容
                content: "Sim卡欠费"
            }).save();
        }else if(message.split(' ')[1]==4){
            new Fault({
                sim:message.split(' ')[0],
                date: new Date(),
                ftype: message.split(' ')[1], //操作内容
                content: "连接不上Sim卡"
            }).save();
        }
    });
    client.end();
    //故障管理
    app.get('/box_management/fault',function(req,res){
        var page = new Page(req.query.num);
        var obj = {
            page: page,
            search: {}
        };
        new Fault().findForPage(obj,function(err, count, pageCount, datas) {
            if (err) {
                console.log("faultM-----" + err);
            }
            var dates=[];
            for(var i=0;i<datas.length;i++){
                dates.push((datas[i].date).toFormat('YYYY-MM-DD HH24:MI:SS'));
            }
            page.pageCount = pageCount;
            res.render('faultM', {
                datas: datas,
                dates:dates,
                page: page
            });
        })
    });
    app.get('/user_system/user_fault',function(req,res){
        var account=req.query.account;
        new Buyer().findAccountByAccount(account,function(err,doc){
            var buyer_id=doc.buyer_id;
            new BoxBuyer().findIdsByBuyer(buyer_id,function(datas) {
                if (datas.length > 0) {
                    var boxes=[];
                    for(var i=0;i<datas.length;i++){
                        boxes.push(datas[i].box_id);
                    }
                    var options={box_id:{$in:boxes}};
                    new Sim().findUserSimById(options,function(err,datas){
                        var sims=[];
                        for(var i=0;i<datas.length;i++){
                            sims.push(datas[i].sim);
                        }
                        var page = new Page(req.query.num);
                        var obj = {
                            page: page,
                            search: {sim:{$in:sims}}
                        };
                        new Fault().findForPage(obj,function(err, count, pageCount, datas) {
                            if (err) {
                                console.log("faultM-----" + err);
                            }
                            var dates=[];
                            for(var i=0;i<datas.length;i++){
                                dates.push((datas[i].date).toFormat('YYYY-MM-DD HH24:MI:SS'));
                            }
                            page.pageCount = pageCount;
                            console.log(page.pageCount);
                            res.render('user_fault', {
                                datas: datas,
                                dates:dates,
                                page: page,
                                account:account
                            });
                        })
                    });

                }else{
                    req.flash('error', '您没有绑定Sim卡.');
                    return res.redirect('/user_system/main');
                }
            });
        });
    });
    app.get('/user_system/user_update_pwd',function(req,res){
        var account=req.query.account;
        res.render('user_update_pwd',{
            account:account
        });
    });
    app.post('/user_system/user_update_pwd',function(req,res){
        var account=req.body.account;
        var opwd=req.body.opwd;
        var password=req.body.npwd1;
        new Buyer().findPwdByAcc(account,function(err,datas){
            if(err){
                console.log(err);
                return res.render('update_pwd',{
                    error:'服务器繁忙，请稍后再试！'
                });
            }
            if(datas) {
                console.log(datas+"-------------------");
                if (opwd != datas.password) {
                    return res.render('update_pwd', {
                        error: '旧密码不正确，请重新输入！'
                    });
                }
                new Buyer().updatePwd(account,password,function(err){
                    console.log(err);
                    new Buyer().findPwdByAcc(account,function(err,datas){
                        req.session.user=datas;
                        req.flash('success', '密码修改成功.');
                        return res.redirect('/user_system/user_update_pwd');
                    });

                });
            }
        });
    });
};